<template>
    <div class="container">
        <el-form :model="searchForm" ref="searchFormRef" label-width="80px" class="mb-4"
            style="display: flex; align-items: center; flex-wrap: wrap;">
            <el-row :gutter="20" style="flex: 1; display: flex;">
                <el-col :span="6">
                    <el-form-item label="入库单号:">
                        <el-input v-model="searchForm.InboundNum" placeholder="输入入库单号" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="单据类型">
                        <el-select v-model.number="searchForm.Storage" placeholder="请选择">
                            <el-option label="原材料入库" value="101"></el-option>
                            <el-option label="成品入库" value="102"></el-option>
                            <el-option label="销售退货入库" value="103"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="入库状态">
                        <el-select v-model.number="searchForm.OutAuditstatus" placeholder="请选择">
                            <el-option label="待处理" value="101"></el-option>
                            <el-option label="处理中" value="102"></el-option>
                            <el-option label="已通过" value="103"></el-option>
                            <el-option label="已拒绝" value="104"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-button type="primary" @click="mockData" style="margin-left: 10px;">
                查询
            </el-button>
            <el-button @click="handleReset" style="margin-left: 10px;">
                重置
            </el-button>
        </el-form>

        <div class="export-button-container">
            <el-button @click="addLeage">新增</el-button>
            <el-button @click="batchExport">编辑</el-button>
            <el-button @click="batchExport">删除</el-button>
            <el-button @click="mockData">刷新</el-button>
            <el-button @click="batchExport">导出</el-button>
        </div>

        <!-- 数据表格 -->
        <el-table :data="tableData" ref="tableRef" style="width: 100%">
            <el-table-column type="selection">
            </el-table-column>
            <el-table-column prop="inboundNum" label="订单号" />
            <el-table-column prop="proName" label="产品名称" />
            <el-table-column prop="proId" label="产品编号" />
            <el-table-column prop="batch" label="批次" />
            <el-table-column prop="specifications" label="规格" />
            <el-table-column prop="quantity" label="数量" />
            <el-table-column prop="binlocation" label="库位" />
            <el-table-column prop="storage" label="入库类型">
                <template #default="scope">
                    {{ scope.row.storage == 101 ? "原材料入库" : "" }}
                    {{ scope.row.storage == 102 ? "成品入库" : "" }}
                    {{ scope.row.storage == 103 ? "销售退货入库" : "" }}
                </template>
            </el-table-column>
            <el-table-column prop="supplier" label="供应商" />
            <el-table-column prop="creator" label="制单人" />
            <el-table-column prop="outAuditstatus" label="状态">
                <template #default="scope">
                    {{ scope.row.outAuditstatus == 101 ? "待处理" : "" }}
                    {{ scope.row.outAuditstatus == 102 ? "处理中" : "" }}
                    {{ scope.row.outAuditstatus == 103 ? "已通过" : "" }}
                    {{ scope.row.outAuditstatus == 104 ? "已拒绝" : "" }}
                </template>
            </el-table-column>
            <el-table-column prop="reviewer" label="审核人" />
            <el-table-column prop="outAuditTime" label="审核时间">
                <template #default="scope">
                    {{ scope.row.outAuditTime ? scope.row.outAuditTime.substring(0, 10) : "" }}
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" min-width="120">
                <template #default="scope">
                    <el-button link type="primary" size="small" @click="showDetail(scope.row.inboundNum)">
                        查看
                    </el-button>
                    <el-button link type="primary" size="small" @click="handleClick(scope.row.id)">
                        删除
                    </el-button>
                    <el-button link type="primary" size="small" @click="Update(scope.row.inboundNum)">
                        修改
                    </el-button>
                    <el-button link type="primary" size="small" @click.stop="ShenPi(scope.row.id)">审批</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <div style=" display: flex; align-items: center; gap: 8px;">
        <el-button @click="selectAll">全选</el-button>
        <el-button @click="reverseSelect">反选</el-button>
        <el-button @click="batchHandle">批量操作</el-button>
        <div style="flex: 1;"></div>
        <el-pagination v-model:current-page="searchForm.pageIndex" v-model:page-size="searchForm.pageSize"
            :page-sizes="[1, 10, 20, 30]" :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="searchForm.totalCount" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <!-- 入库详情 -->
    <el-dialog title="入库单详情" v-model="detailDialogVisible" width="60%">
        <!-- 上半部分信息 -->
        <div class="detail-info">
            <!-- 第一行：入库单号、入库单类型、入库状态 -->
            <div class="info-row">
                <span class="label">入库单号：</span>
                <span>{{ detailInfo.inboundNum }}</span>
            </div>
            <div class="info-row">
                <span class="label">入库单类型：</span>
                <span>{{ detailInfo.storage === 101 ? '原材料入库' : detailInfo.storage === 102 ? '成品入库' : detailInfo.storage
                    === 103 ? '销售退货入库' : '' }}</span>
            </div>
            <div class="info-row">
                <span class="label">入库状态：</span>
                <span>{{ detailInfo.outAuditstatus === 101 ? '待处理' : detailInfo.outAuditstatus === 102 ? '处理中' :
                    detailInfo.outAuditstatus === 103 ? '已通过' : detailInfo.outAuditstatus === 104 ? '已拒绝' : '' }}</span>
            </div>

            <!-- 第二行：供应商编号、供应商名称、联系人 -->
            <div class="info-row">
                <span class="label">供应商编号：</span>
                <span>{{ detailInfo.supplierID }}</span>
            </div>
            <div class="info-row">
                <span class="label">供应商名称：</span>
                <span>{{ detailInfo.supplierName }}</span>
            </div>
            <div class="info-row">
                <span class="label">联系人：</span>
                <span>{{ detailInfo.supplierPeople }}</span>
            </div>

            <!-- 第三行：电话、制单人、制单日期 -->
            <div class="info-row">
                <span class="label">电话：</span>
                <span>{{ detailInfo.supplierPhone }}</span>
            </div>
            <div class="info-row">
                <span class="label">制单人：</span>
                <span>{{ detailInfo.creator }}</span>
            </div>
            <div class="info-row">
                <span class="label">制单日期：</span>
                <span>{{ detailInfo.outCreationTime ? detailInfo.outCreationTime.substring(0, 10) : "" }}</span>
            </div>

            <!-- 新增关联单号 -->
            <div class="info-row">
                <span class="label">关联单号：</span>
                <span>{{ detailInfo.associatedNum }}</span>
            </div>

            <!-- 备注与审核原因 -->
            <div class="info-row">
                <span class="label">备注：</span>
                <span>{{ detailInfo.rember || '无' }}</span>
            </div>
            <div class="info-row">
                <span class="label">审核原因：</span>
                <span>{{ detailInfo.shenRember || '同意' }}</span>
            </div>
        </div>

        <!-- 下半部分表格 -->
        <el-table :data="tableDatas" style="margin-top: 20px">
            <el-table-column prop="proId" label="产品编码" width="150">
                <template #default="scope">
                    <span v-if="Array.isArray(scope.row.proId)">
                        <span v-for="(id, index) in scope.row.proId" :key="index">{{ id }}{{ index <
                            scope.row.proId.length - 1 ? ', ' : '' }}</span>
                        </span>
                        <span v-else>{{ scope.row.proId }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="proName" label="产品名称" width="200">
                <template #default="scope">
                    <span v-if="Array.isArray(scope.row.proName)">
                        <span v-for="(name, index) in scope.row.proName" :key="index">{{ name }}{{ index <
                            scope.row.proName.length - 1 ? ', ' : '' }}</span>
                        </span>
                        <span v-else>{{ scope.row.proName }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="specifications" label="规格" width="100">
                <template #default="scope">
                    <span v-if="Array.isArray(scope.row.specifications)">
                        <span v-for="(spec, index) in scope.row.specifications" :key="index">{{ spec }}{{ index <
                            scope.row.specifications.length - 1 ? ', ' : '' }}</span>
                        </span>
                        <span v-else>{{ scope.row.specifications }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="batch" label="批次" width="150">
                <template #default="scope">
                    <span v-if="Array.isArray(scope.row.batch)">
                        <span v-for="(batch, index) in scope.row.batch" :key="index">{{ batch }}{{ index <
                            scope.row.batch.length - 1 ? ', ' : '' }}</span>
                        </span>
                        <span v-else>{{ scope.row.batch }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="unitprice" label="单价" width="120">
                <template #default="scope">
                    <span v-if="Array.isArray(scope.row.unitprice)">
                        <span v-for="(unitprice, index) in scope.row.unitprice" :key="index">{{
                            parseFloat(unitprice).toFixed(2) }}{{ index < scope.row.unitprice.length - 1 ? ', ' : ''
                                }}</span>
                        </span>
                        <span v-else>{{ parseFloat(scope.row.unitprice).toFixed(2) }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="uNumber" label="入库数" width="120">
                <template #default="scope">
                    <span v-if="Array.isArray(scope.row.uNumber)">
                        <span v-for="(uNumber, index) in scope.row.uNumber" :key="index">{{ uNumber }}{{ index <
                            scope.row.uNumber.length - 1 ? ', ' : '' }}</span>
                        </span>
                        <span v-else>{{ scope.row.uNumber }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="price" label="总价" width="150">
                <template #default="scope">
                    <span v-if="Array.isArray(scope.row.price)">
                        <span v-for="(p, index) in scope.row.price" :key="index">{{ parseFloat(p).toFixed(2) }}{{ index
                            < scope.row.price.length - 1 ? ', ' : '' }}</span>
                        </span>
                        <span v-else>{{ parseFloat(scope.row.price).toFixed(2) }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="binlocation" label="库位" width="250">
                <template #default="scope">
                    <span v-if="Array.isArray(scope.row.binlocation)">
                        <span v-for="(location, index) in scope.row.binlocation" :key="index">{{ location }}{{ index <
                            scope.row.binlocation.length - 1 ? ', ' : '' }}</span>
                        </span>
                        <span v-else>{{ scope.row.binlocation }}</span>
                </template>
            </el-table-column>
        </el-table>

        <div style="text-align: right; margin-top: 20px">
            <el-button @click="detailDialogVisible = false">关闭</el-button>
        </div>
    </el-dialog>
    <!-- 审批 -->
    <el-dialog title="审批" v-model="approvalDialogVisible" width="60%">
        <!-- 上半部分信息 -->
        <div class="detail-info">
            <!-- 第一行：入库单号、入库单类型、入库状态 -->
            <div class="info-row">
                <span class="label">入库单号：</span>
                <span>{{ detailInfo.inboundNum }}</span>
            </div>
            <div class="info-row">
                <span class="label">入库单类型：</span>
                <span>{{ detailInfo.storage === 101 ? '原材料入库' : detailInfo.storage === 102 ? '成品入库' : detailInfo.storage
                    ===
                    103 ? '销售退货入库' : '' }}</span>
            </div>
            <div class="info-row">
                <span class="label">入库状态：</span>
                <span>{{ detailInfo.outAuditstatus === 101 ? '待处理' : detailInfo.outAuditstatus === 102 ? '处理中' :
                    detailInfo.outAuditstatus === 103 ? '已通过' : detailInfo.outAuditstatus === 104 ? '已拒绝' : '' }}</span>
            </div>

            <!-- 第二行：供应商编号、供应商名称、联系人 -->
            <div class="info-row">
                <span class="label">供应商编号：</span>
                <span>{{ detailInfo.supplierID }}</span>
            </div>
            <div class="info-row">
                <span class="label">供应商名称：</span>
                <span>{{ detailInfo.supplierName }}</span>
            </div>
            <div class="info-row">
                <span class="label">联系人：</span>
                <span>{{ detailInfo.supplierPeople }}</span>
            </div>

            <!-- 第三行：电话、制单人、制单日期 -->
            <div class="info-row">
                <span class="label">电话：</span>
                <span>{{ detailInfo.supplierPhone }}</span>
            </div>
            <div class="info-row">
                <span class="label">制单人：</span>
                <span>{{ detailInfo.creator }}</span>
            </div>
            <div class="info-row">
                <span class="label">制单日期：</span>
                <span>{{ detailInfo.outCreationTime ? detailInfo.outCreationTime.substring(0, 10) : "" }}</span>
            </div>

            <!-- 新增关联单号 -->
            <div class="info-row">
                <span class="label">关联单号：</span>
                <span>{{ detailInfo.associatedNum }}</span>
            </div>

            <!-- 备注与审核原因 -->
            <div class="info-row">
                <span class="label">备注：</span>
                <span>{{ detailInfo.rember || '无' }}</span>
            </div>
            <div class="info-row">
                <span class="label">审核原因：</span>
                <el-input v-model="detailInfo.pid" type="textarea" :autosize="{ minRows: 3, maxRows: 6 }"></el-input>
            </div>
        </div>

        <!-- 下半部分表格 -->
        <el-table :data="tableDatas" style="margin-top: 20px">
            <el-table-column prop="proId" label="产品编码" width="150">
                <template #default="scope">
                    <span v-if="Array.isArray(scope.row.proId)">
                        <span v-for="(id, index) in scope.row.proId" :key="index">{{ id }}{{ index <
                            scope.row.proId.length - 1 ? ', ' : '' }}</span>
                        </span>
                        <span v-else>{{ scope.row.proId }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="proName" label="产品名称" width="200">
                <template #default="scope">
                    <span v-if="Array.isArray(scope.row.proName)">
                        <span v-for="(name, index) in scope.row.proName" :key="index">{{ name }}{{ index <
                            scope.row.proName.length - 1 ? ', ' : '' }}</span>
                        </span>
                        <span v-else>{{ scope.row.proName }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="specifications" label="规格" width="100">
                <template #default="scope">
                    <span v-if="Array.isArray(scope.row.specifications)">
                        <span v-for="(spec, index) in scope.row.specifications" :key="index">{{ spec }}{{ index <
                            scope.row.specifications.length - 1 ? ', ' : '' }}</span>
                        </span>
                        <span v-else>{{ scope.row.specifications }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="batch" label="批次" width="150">
                <template #default="scope">
                    <span v-if="Array.isArray(scope.row.batch)">
                        <span v-for="(batch, index) in scope.row.batch" :key="index">{{ batch }}{{ index <
                            scope.row.batch.length - 1 ? ', ' : '' }}</span>
                        </span>
                        <span v-else>{{ scope.row.batch }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="unitprice" label="单价" width="120">
                <template #default="scope">
                    <span v-if="Array.isArray(scope.row.unitprice)">
                        <span v-for="(unitprice, index) in scope.row.unitprice" :key="index">{{
                            parseFloat(unitprice).toFixed(2) }}{{ index < scope.row.unitprice.length - 1 ? ', ' : ''
                                }}</span>
                        </span>
                        <span v-else>{{ parseFloat(scope.row.unitprice).toFixed(2) }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="uNumber" label="入库数" width="120">
                <template #default="scope">
                    <span v-if="Array.isArray(scope.row.uNumber)">
                        <span v-for="(uNumber, index) in scope.row.uNumber" :key="index">{{ uNumber }}{{ index <
                            scope.row.uNumber.length - 1 ? ', ' : '' }}</span>
                        </span>
                        <span v-else>{{ scope.row.uNumber }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="price" label="总价" width="150">
                <template #default="scope">
                    <span v-if="Array.isArray(scope.row.price)">
                        <span v-for="(p, index) in scope.row.price" :key="index">{{ parseFloat(p).toFixed(2) }}{{ index
                            < scope.row.price.length - 1 ? ', ' : '' }}</span>
                        </span>
                        <span v-else>{{ parseFloat(scope.row.price).toFixed(2) }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="binlocation" label="库位" width="250">
                <template #default="scope">
                    <span v-if="Array.isArray(scope.row.binlocation)">
                        <span v-for="(location, index) in scope.row.binlocation" :key="index">{{ location }}{{ index <
                            scope.row.binlocation.length - 1 ? ', ' : '' }}</span>
                        </span>
                        <span v-else>{{ scope.row.binlocation }}</span>
                </template>
            </el-table-column>
        </el-table>

        <div style="text-align: right; margin-top: 20px">
            <el-button @click="approve()">审核通过</el-button>
            <el-button @click="reject()">审核不通过</el-button>
            <el-button @click="approvalDialogVisible = false">关闭</el-button>
        </div>
    </el-dialog>
</template>

<script setup lang="ts">
import axios from 'axios';
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElTable } from 'element-plus';
import { saveAs } from 'file-saver';
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router';
import { KongaUrl } from '@/axios/axiosHelp'

const router = useRouter();
const route = useRoute();

// 接口地址配置
const API_CONFIG = {
    STORE_QUERY: '/wangjunlong/api/Store/StoreQuser',
    STORE_DETAIL: '/wangjunlong/api/Store/StoreOnly',
    STORE_DELETE: '/wangjunlong1/api/Store/StoreDelete',
    STORE_EXPORT: '/wangjunlong/api/Store/ExportOrderList'
};

interface TableRow {
    id: number;
    pid: number;
    inboundNum: string;
    associatedNum: string;
    batch: string | string[];
    specifications: string | string[];
    quantity: string | string[];
    totalprice: string;
    binlocation: string | string[];
    storage: number;
    supplier: string;
    supplierID: string;
    supplierName: string;
    supplierPeople: string;
    supplierPhone: string;
    creator: string;
    reviewer: string;
    outAuditTime: string;
    outAuditstatus: number;
    outCreationTime: string;
    rember: string;
    isDelete: number;
    price: string | string[];
    proId: string | string[];
    proName: string | string[];
}

const searchForm = reactive({
    InboundNum: '',
    Storage: '',
    OutAuditstatus: '',
    pageIndex: 1,
    pageSize: 15,
    totalPage: 0,
    totalCount: 0,
});

const tableData = ref<TableRow[]>([]);
const tableRef = ref<InstanceType<typeof ElTable>>();

// 弹窗相关变量
const detailDialogVisible = ref(false);
const approvalDialogVisible = ref(false);

// 统一错误处理函数
const handleAxiosError = (error: any) => {
    if (error.response) {
        console.error('请求失败，状态码:', error.response.status);
        console.error('响应数据:', error.response.data);
        ElMessage.error(`请求失败，状态码: ${error.response.status}`);
    } else if (error.request) {
        console.error('请求已发送，但没有收到响应');
        ElMessage.error('请求已发送，但没有收到响应');
    } else {
        console.error('请求出错:', error.message);
        ElMessage.error('网络请求失败，请检查连接');
    }
};

// 提取重复的数据处理逻辑
const processDetailData = (data: any) => {
    const parseData = (str: string) => {
        return (str.match(/\{([^}]+)\}/g) || []).map(item => item.slice(1, -1));
    };
    const proIds = parseData(data.proId);
    const proNames = parseData(data.proName);
    const specifications = parseData(data.specifications);
    const batch = parseData(data.batch);
    const unitprice = parseData(data.unitprice).map(Number);
    const uNumber = parseData(data.uNumber);
    const price = parseData(data.price).map(Number);
    const binlocation = parseData(data.binlocation);

    const processedData = proIds.map((id, index) => ({
        proId: id,
        proName: proNames[index] || '',
        specifications: specifications[index] || '',
        batch: batch[index] || '',
        unitprice: unitprice[index] || 0,
        uNumber: uNumber[index] || '',
        price: price[index] || 0,
        binlocation: binlocation[index] || ''
    }));

    return processedData;
};

onMounted(() => {
    mockData();
});

const mockData = async () => {
    try {
        const res = await KongaUrl<{
            code: number;
            msg: string;
            data: {
                list: TableRow[];
                totalPage: number;
                totalCount: number;
            };
        }>("/wangjunlong/api/Store/StoreQuser", {
            params: {
                InboundNum: searchForm.InboundNum,
                Storage: searchForm.Storage,
                OutAuditstatus: searchForm.OutAuditstatus,
                PageIdex: searchForm.pageIndex,
                PageSize: searchForm.pageSize,
            }
        });

        if (res.data.code === 210) {
            tableData.value = res.data.data.list;
            searchForm.totalPage = res.data.data.totalPage;
            searchForm.totalCount = res.data.data.totalCount;
            console.log('数据加载完成');
        } else {
            console.error('查询失败:', res.data.msg);
            ElMessage.error(res.data.msg);
        }
    } catch (error) {
        handleAxiosError(error);
    }
};

const handleSizeChange = (size: number) => {
    searchForm.pageSize = size;
    mockData();
};

const handleCurrentChange = (page: number) => {
    searchForm.pageIndex = page;
    mockData();
};

const handleReset = () => {
    searchForm.InboundNum = '';
    searchForm.Storage = '';
    searchForm.OutAuditstatus = '';
    searchForm.pageIndex = 1;
    mockData();
};

// 全选
const selectAll = () => {
    if (tableRef.value) {
        tableData.value.forEach(row => {
            tableRef.value?.toggleRowSelection(row, true);
        });
        console.log('全选操作执行');
    } else {
        console.log('表格引用未初始化');
    }
};

// 反选
const reverseSelect = () => {
    if (tableRef.value) {
        tableData.value.forEach(row => {
            tableRef.value?.toggleRowSelection(row);
        });
        console.log('反选操作执行');
    } else {
        console.log('表格引用未初始化');
    }
};

// 批量操作
const batchHandle = () => {
    const selected = tableRef.value?.getSelectionRows() || [];
    if (selected.length === 0) {
        ElMessage.warning('请选择数据');
        return;
    }
    console.log('批量操作数据:', selected);
    // 这里添加实际业务逻辑（如调用接口）
};

// 处理复选框选择状态改变
const handleCheckboxChange = (val: boolean, row: TableRow) => {
    tableRef.value?.toggleRowSelection(row, val);
};

// 批量导出功能
const batchExport = async () => {
    const selected = tableRef.value?.getSelectionRows() || [];
    if (selected.length === 0) {
        ElMessage.warning('请选择要导出的数据');
        return;
    }
    const productIds = selected.map(item => item.id);

    try {
        const res = await KongaUrl(API_CONFIG.STORE_EXPORT, {
            params: {
                id: productIds
            },
            paramsSerializer: (params) => {
                const parts = [];
                for (const key in params) {
                    if (Array.isArray(params[key])) {
                        params[key].forEach((value) => {
                            parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
                        });
                    } else {
                        parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`);
                    }
                }
                return parts.join('&');
            },
            responseType: 'blob'
        });
        const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        saveAs(blob, '批量库存数据.xlsx');
    } catch (error) {
        ElMessage.error('批量导出失败，请联系管理员');
        console.error('批量导出错误:', error);
    }
};

const handleClick = (id: number) => {
    ElMessageBox.confirm(
        '确定删除吗?',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            KongaUrl.post(`${API_CONFIG.STORE_DELETE}?Id=${id}`).then((res) => {
                if (res.data.code === 204) {
                    ElMessage({
                        message: '删除成功',
                        type: 'success',
                    })
                    mockData();
                } else {
                    ElMessage.error('删除失败')
                    mockData();
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消',
            })
        })
};

const addLeage = () => {
    // 这里原代码参数问题，暂时保留逻辑，若有需要可修改
    router.push('/Store')
};

const tableDatas = ref<TableRow[]>([]);
const detailInfo = ref<TableRow>({} as TableRow);
// 查看
const showDetail = async (inboundNum: string) => {
    try {
        console.log('开始请求详情数据，入库单号:', inboundNum);
        const requestUrl = `/wangjunlong/api/Store/StoreOnly?InboundNum=${inboundNum}`
        //const requestUrl = `${API_CONFIG.STORE_DETAIL}?InboundNum=${inboundNum}`;
        console.log('请求 URL:', requestUrl); // 添加这行代码，打印请求的 URL
        const res = await KongaUrl(requestUrl);
        console.log('详情数据请求响应:', res.data);
        if (res.data.code === 0 && res.data.data && res.data.data.length > 0) {
            detailInfo.value = res.data.data[0];
            tableDatas.value = res.data.data.map(item => ({
                ...item,
                unitprice: parseFloat(item.unitprice).toFixed(2),
                price: parseFloat(item.price).toFixed(2)
            }));
            detailDialogVisible.value = true;
            nextTick(() => {
                console.log('数据更新，尝试重新渲染');
            });
        } else {
            console.error('未获取到详情数据');
            ElMessage.error('未获取到详情数据');
        }
    } catch (error) {
        console.error('获取详情数据时出错:', error);
        handleAxiosError(error);
    }
};

// 编辑
const Update = (inboundNum: number) => {
    router.push(`/StoreUpdate?id=${inboundNum}`)
};

const ShenPi = async (id: number) => {
    try {
        console.log('开始请求审批详情数据，ID:', id);
        const res = await KongaUrl(`${API_CONFIG.STORE_DETAIL}?Id=${id}`);
        console.log('审批详情数据请求响应:', res.data);
        if (res.data.data && res.data.data.length > 0) {
            const data = res.data.data[0];
            tableDatas.value = processDetailData(data);
            detailInfo.value = data;
            approvalDialogVisible.value = true;
            nextTick(() => {
                console.log('数据更新，尝试重新渲染');
            });
        } else {
            console.error('未获取到审批详情数据');
            ElMessage.error('未获取到审批详情数据');
        }
    } catch (error) {
        console.error('获取审批详情数据时出错:', error);
        handleAxiosError(error);
    }
};
//审核通过
const approve = () => {
    // 假设 id 是当前审批的入库单的 ID，从 detailInfo 中获取
    const id = detailInfo.value.id;
    // 假设 form 是表单数据对象，这里为了示例假设从 detailInfo 中获取部分数据
    const form = detailInfo.value;
    // 假设 Store 是一个包含用户信息的对象，这里简单处理
    const Store = { user: { userName: '当前用户名' } };
    // 假设 products 是当前入库单的产品数据数组，从 tableDatas 中获取
    const products = tableDatas.value;

    const submitData = {
        id: id,
        pid: 1,
        inboundNum: String(form.inboundNum),
        associatedNum: form.associatedNum,
        batch: products.map(row => `{${row.batch}}`).join(','),
        quantity: products.map(row => `{${row.uNumber}}`).join(','),
        storage: Number(form.storage),
        supplier: "无",
        supplierID: form.supplierID,
        supplierName: form.supplierName,
        supplierPeople: form.supplierPeople,
        supplierPhone: form.supplierPhone,
        creator: Store.user?.userName || '未知用户',
        // 这里原代码没写完，可根据实际情况补充完整
    };

    // 发送审批通过请求
    KongaUrl('/wangjunlong/api/Store/StoreApprove', submitData)
        .then(response => {
            if (response.data.code === 200) {
                ElMessage.success('审批通过');
                approvalDialogVisible.value = false;
                mockData();
            } else {
                ElMessage.error('审批失败');
            }
        })
        .catch(error => {
            handleAxiosError(error);
        });
};

//审核不通过
const reject = () => {
    const id = detailInfo.value.id;
    const form = detailInfo.value;
    const Store = { user: { userName: '当前用户名' } };
    const products = tableDatas.value;

    const submitData = {
        id: id,
        pid: 2,
        inboundNum: String(form.inboundNum),
        associatedNum: form.associatedNum,
        batch: products.map(row => `{${row.batch}}`).join(','),
        quantity: products.map(row => `{${row.uNumber}}`).join(','),
        storage: Number(form.storage),
        supplier: "无",
        supplierID: form.supplierID,
        supplierName: form.supplierName,
        supplierPeople: form.supplierPeople,
        supplierPhone: form.supplierPhone,
        creator: Store.user?.userName || '未知用户',
        // 这里原代码没写完，可根据实际情况补充完整
    };

    // 发送审批不通过请求
    KongaUrl('/wangjunlong/api/Store/StoreReject', submitData)
        .then(response => {
            if (response.data.code === 200) {
                ElMessage.success('审批不通过');
                approvalDialogVisible.value = false;
                mockData();
            } else {
                ElMessage.error('修改失败');
            }
        })
        .catch(error => {
            handleAxiosError(error);
        });
};
</script>

<style scoped>
.container {
    padding: 20px;
}

.mb-4 {
    margin-bottom: 16px;
}

.export-button-container {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 16px;
}

.detail-info {
    margin-bottom: 20px;
    display: flex;
    flex-wrap: wrap;
}

.info-row {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    width: 50%;
}

.label {
    width: 120px;
    font-weight: 500;
    margin-right: 10px;
    text-align: right;
}

.el-table th,
.el-table td {
    border: 1px solid #e4e7ed;
}

.el-table th {
    background-color: #f5f7fa;
}

.el-button {
    margin: 0 5px;
}
</style>